package task

import (
	"github.com/gin-gonic/gin"
	"message-center/pkg/gconfig"
	"message-center/pkg/gerrno"
	"message-center/pkg/ginput"
	"message-center/pkg/gmail"
	"net/http"
)

/**
 * @api {POST} /api/v1/send/task/mail mail消息
 * @apiVersion 1.0.0
 * @apiName  health
 * @apiGroup  task
 * @apiDescription 发送mail
 * @apiExample {curl} Example usage:
 * curl -X POST -H "Content-Type:application/json" -d '{"To":"13838130517@163.com", "Subject":"开发测试", "ContentType":"text/plain", "Body": "发送邮件测试"}' -i http://localhost:9090/api/v1/task/send/mail
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": 200,
 *       "msg": "ok",
 *       "data": "发送成功！"
 *     }
 */
func SendMail(c *gin.Context) {
	var (
		rsp     = ginput.Gin{C: c}
		reqData = make(map[string]string)
	)

	httpCode, errCode := rsp.ParamParse(&reqData)

	if httpCode != http.StatusOK {
		rsp.SendJSON(httpCode, errCode, nil)
		return
	}

	// 发送邮件测试
	host := gconfig.MailConfig.Host
	user := gconfig.MailConfig.User
	pwd := gconfig.MailConfig.Pwd
	port := gconfig.MailConfig.Port

	mail := gmail.NewMail(host, port, user, pwd)

	header := map[string]string{
		"From":    gconfig.MailConfig.From,
		"To":      reqData["To"],
		"Subject": reqData["Subject"],
	}

	contentType := reqData["ContentType"]
	body := reqData["Body"]

	mail.SetParams(header, contentType, body)
	err := mail.Send()

	if err != nil {
		rsp.SendJSON(http.StatusInternalServerError, gerrno.ERROR, err)
		return
	}

	res := "发送成功！"
	rsp.SendJSON(http.StatusOK, gerrno.SUCCESS, res)
}
